﻿//**************************************************
//Description:  游戏管理
//Author:       leubooth
//Date:         2016.11.03
//**************************************************

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class GameManager : MonoBehaviour
{
    /// <summary>
    /// 单件
    /// </summary>
    public static GameManager Instance;

    /// <summary>
    /// 游戏状态机
    /// </summary>
    public GameState state = GameState.None;

    /// <summary>
    /// 关卡列表
    /// </summary>
    public List<string> levels = new List<string>();

    void Awake()
    {
        Instance = this;

        InitLevels();
    }

    void Start ()
    {
        //初始化格子系统
        //GridSystem.Instance.InitGridSystem(1);
        //GridSystem.Instance.InitGridSystem("2");

        //初始化元素系统
        //ItemSystem.Instance.InitItemSystem();

        //将状态机转换为游戏状态
        //state = GameState.Playing;
	}

    /// <summary>
    /// 读取文件夹获取文件名数组
    /// </summary>
    void InitLevels()
    {
        DirectoryInfo di = new DirectoryInfo(LevelDataManager.levelDataPath);
        foreach (FileInfo fi in di.GetFiles("*.txt"))
        {
            levels.Add(Path.GetFileNameWithoutExtension(fi.FullName));
        }
    }

    /// <summary>
    /// 载入关卡
    /// </summary>
    /// <param name="levelName"></param>
    public void LoadLevel(string levelName)
    {
        GridSystem.Instance.InitGridSystem(levelName);

        ItemSystem.Instance.InitItemSystem();

        state = GameState.Playing;
    }

    void Update()
    {
        switch (state)
        {
            case GameState.Playing:
                PlayingLogic();
                break;
        }
    }

    /// <summary>
    /// 游戏运行逻辑
    /// </summary>
    void PlayingLogic()
    {
        //点击事件
        if (Input.GetMouseButtonDown(0))
        {
            if (ItemSystem.Instance.closeList.Count > 0) return;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.transform.GetComponent<Item>())
                {
                    Item item = hit.transform.GetComponent<Item>();
                    //Debug.Log("鼠标点中------" + item.x + ":" + item.y);

                    state = GameState.Waiting;

                    //计算
                    ItemSystem.Instance.Calculate(item);

                    //刷新元素
                    ItemSystem.Instance.Refresh();
                }
            }
        }
    }
}

/// <summary>
/// 游戏状态机
/// </summary>
public enum GameState
{
    None,
    Playing,
    Waiting
}